package edu.whu.powersoap;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.cloud.CloudPoiInfo;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviPara;

public class JobDetailActivity extends Activity {
	private final static String TAG = "JobDetailActivity";
	private Context mContext;
	public LocationClient mLocationClient = null;
	public BDLocationListener myListener = new MyLocationListenner();
	private MapView mMapView;
	private final int startTimer = 0x100;
	private final int sTimer = 0x010;
	public static BaiduMap mBaiduMap;
	private BDLocation mLocation;
	boolean isFirstLoc = true;// 是否首次定位
	public Timer timer = new Timer();
	public Intent intent ;
	private String mPoi;
	private LocationClient mLocClient;
	private LayoutInflater mLayoutInflater;
	public String username = MainActivity.user;
	public String number;
	public ArrayList<LatLng> routeList = new ArrayList<LatLng>();
	public Dialog dialogm ;
	private Handler handler = new Handler() {		
		@Override
		public void handleMessage(Message msg) {	
			
//			Log.i(TAG, "handleMessage start.....");		
			//记录坐标
//			switch (msg.what) {
//			
//	            case 0x100: 
////	            	System.exit(0);	 
//	            	ContentResolver cr = mContext.getContentResolver();
//	            	ContentValues values = new ContentValues();
//	            	Double a = mLocation.getLatitude();
//	            	Double b = mLocation.getLongitude();
//					values.put(RouteProvider.VOLUMN_NUMBER,intent.getStringExtra("number"));				
////					values.put(RouteProvider.VOLUMN_ROU_LIST,a+ ","+ b);	
//					 Log.i(TAG, "runbbbbbbbbbbbb...");
//					routeList.add(new LatLng(mLocation.getLatitude(),mLocation.getLongitude()));					
//					Uri uri = cr.insert(RouteProvider.CONTENT_URI, values);	
//					if(routeList.size()>=3){
//					    	   Log.i(TAG, "runmmmm...");
//					    	   msg = handler.obtainMessage(sTimer);					    	 
//					    	   msg.sendToTarget();					    	   
//					}
//					break;
//					
//	            case 0x010:	 
//	            	Log.i(TAG, "runaaaaaaaaaaaaaaaaa...");
//	            	OverlayOptions rop = new PolylineOptions().color(Color.BLUE).points(routeList).visible(true);
//	            	mBaiduMap.addOverlay(rop);
//	            	break;
//
//			}   
			
            super.handleMessage(msg);  
			BitmapDescriptor bd = BitmapDescriptorFactory
					.fromResource(R.drawable.icon_gcoding);
			LatLng ll;
			LatLngBounds.Builder builder = new LatLngBounds.Builder();
			String[] posList = mPoi.split(";");
			String[] pos = posList[0].split(",");
//			String[] pos = mPoi.split(",");
//			Log.i(TAG, "pos0=" + pos[0] + ", pos1=" + pos[1]);
			ll = new LatLng(Double.parseDouble(pos[0]),
					Double.parseDouble(pos[1]));
			OverlayOptions oo = new MarkerOptions().icon(bd).position(ll);
			mBaiduMap.addOverlay(oo);
			builder.include(ll);

			ll = new LatLng(mLocation.getLatitude(), mLocation.getLongitude());
			builder.include(ll);

			LatLngBounds bounds = builder.build();
			MapStatusUpdate u = MapStatusUpdateFactory.newLatLngBounds(bounds);
			mBaiduMap.animateMapStatus(u);
//          mark 
			Button btng,btnf,btnm;
			btng = (Button) findViewById(R.id.btn_go);
			btnf = (Button) findViewById(R.id.btn_finish);
//			btnm = (Button) findViewById(R.id.btn_mark);
//			btnm.setOnClickListener(new OnClickListener(){
//
//				@Override
//				public void onClick(View v) {
//					
//				String mark = "marked";		            
//	            ContentValues values = new ContentValues();	
//	            ContentResolver cr = mContext.getContentResolver();
//	            number = intent.getStringExtra("number");
//	            values.put(MarkProvider.VOLUMN_NUMBER, number);
//	            values.put(MarkProvider.VOLUMN_FLAG, mark);	            
//	            cr.insert(MarkProvider.CONTENT_URI, values);
//					
//				final View markView = mLayoutInflater
//							.inflate(R.layout.mark, null);
//					
//				dialogm = new AlertDialog.Builder(JobDetailActivity.this)
//				.setView(markView)
//				.setTitle("记录")
//				.create();
//				dialogm.show();
//				
//				Button btn1,btn2,btn3,btn4;
//				CheckBox check;
//				check = (CheckBox)markView.findViewById(R.id.check);					
////				btn0 = (Button) markView.findViewById(R.id.btn_noneed);
//				btn1 = (Button) markView.findViewById(R.id.btn_word);
//				btn2 = (Button) markView.findViewById(R.id.btn_photo);
//				btn3 = (Button) markView.findViewById(R.id.btn_video);
//				btn4 = (Button) markView.findViewById(R.id.btn_voice);
//				
//				check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){ 
//		            @Override 
//		            public void onCheckedChanged(CompoundButton buttonView, 
//		                    boolean isChecked) { 
//		                // TODO Auto-generated method stub 
//		                if(isChecked){ 
//		                	Dialog dialog = new AlertDialog.Builder(JobDetailActivity.this)
//							.setMessage("无需记录任何信息")
//							.setTitle("提示")
//							.setNegativeButton("取消", new DialogInterface.OnClickListener(){
//
//								@Override
//								public void onClick(DialogInterface dialog,
//										int which) {
//									dialog.dismiss();
//									dialogm.dismiss();
//									// TODO Auto-generated method stub
//									
//								}
//								
//							})
//							.setPositiveButton("确认",
//									new DialogInterface.OnClickListener() {
//
//										@Override
//										public void onClick(DialogInterface dialog,
//												int which) {
//											String mark = "unmarked";
//											ContentValues values = new ContentValues();	 				            
//								            values.put(MarkProvider.VOLUMN_FLAG, mark);
//											ContentResolver cr = mContext.getContentResolver();
//											cr.update(MarkProvider.CONTENT_URI, values, "number =?", new String[]{number});
//											dialog.dismiss();
//											dialogm.dismiss();
////												JobDetailActivity.this.finish();
//										}
//									}).create();
//					dialog.show();	
//		                }else{ 
//		                	dialogm.dismiss();
//		                } 
//		            } 
//		        });
//
//				btn1.setOnClickListener(new OnClickListener(){
//
//					@Override
//					public void onClick(View v) {
//						final View wordView = mLayoutInflater
//								.inflate(R.layout.mark_word, null);
//						
//			            
//			            Dialog dialog = new AlertDialog.Builder(JobDetailActivity.this)
//			            					.setView(wordView)
//			            					.setNegativeButton("取消", new DialogInterface.OnClickListener(){
//
//												@Override
//												public void onClick(
//														DialogInterface dialog,
//														int which) {
//													
//													dialog.dismiss();
//													dialogm.dismiss();
//													
//												}
//			            					
//			            					})
//			            					.setPositiveButton("确定记录", 
//			            							new DialogInterface.OnClickListener(){
//
//														@Override
//														public void onClick(
//																DialogInterface dialog,
//																int which) {
//												            EditText word = (EditText) wordView.findViewById(R.id.mark_word);
//															ContentValues values = new ContentValues();													
//															ContentResolver cr = mContext.getContentResolver();          
//												            Cursor c = cr.query(MarkProvider.CONTENT_URI, new String[] 
//																	{
//																	MarkProvider.VOLUMN_NUMBER + " as _id",
//																	MarkProvider.VOLUMN_WORD 
//																	}, "number =?", new String[]{number}, null);
//												            c.moveToFirst();
//															int id = c.getColumnIndex(MarkProvider.VOLUMN_WORD);
//															String o_word = c.getString(id);
//															c.close();
//															String n_word = null;
//															if(o_word==null){							
//																n_word = word.getText().toString();
//															}else{
//																n_word = o_word + " ; "+word.getText().toString();
//															}																												
//												            values.put(MarkProvider.VOLUMN_WORD, n_word);
//												            values.put(MarkProvider.VOLUMN_FLAG, "marked");
//															cr.update(MarkProvider.CONTENT_URI, values, "number =?", new String[]{number});
//															
//															dialog.dismiss();
//															dialogm.dismiss();
//														}
//			            						
//			            					}).create();
//			            
//			            dialog.show();
//					}
//					
//				});
//				
//				//mark有待完善
//				btn2.setOnClickListener(new OnClickListener(){
//
//					@Override
//					public void onClick(View v) {
//						 Intent it = new Intent(JobDetailActivity.this, MyCameraActivity.class);
//						 Bundle bundle = new Bundle();
//						 bundle.putString("number", number);
//						 it.putExtras(bundle);
//						 startActivity(it); 
//						 dialogm.dismiss();
//						
//					}
//					
//				});
//				
//				btn3.setOnClickListener(new OnClickListener(){
//
//					@Override
//					public void onClick(View v) {
//						Intent it = new Intent(JobDetailActivity.this, MyVideoActivity.class);
//						Bundle bundle = new Bundle();
//						bundle.putString("number", number);
//						it.putExtras(bundle);
//						startActivity(it); 
//						dialogm.dismiss();
//						
//					}
//					
//				});
//				
//				btn4.setOnClickListener(new OnClickListener(){
//
//						@Override
//						public void onClick(View v) {
//							Intent it = new Intent(JobDetailActivity.this, MyVoiceActivity.class);
//							Bundle bundle = new Bundle();
//							bundle.putString("number", number);
//							it.putExtras(bundle);
//							startActivity(it); 
//							dialogm.dismiss();																										
//						}						
//					});								
//			}						
//		});
		
		
			btnf.setOnClickListener(new OnClickListener(){
				public void onClick(View v) {					
					// 定时器关掉
//					timer.cancel();
					//jobfinished

					Time time = new Time();
					time.setToNow();
					String f_time = time.year + "." + (time.month+1) + "." + time.monthDay +" "+
					time.hour + ":"+ time.minute + ":"+ time.second;
					
					Dialog dialog = new AlertDialog.Builder(JobDetailActivity.this)
							.setMessage("任务完成")
							.setTitle("提示")
							.setPositiveButton("确认",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(DialogInterface dialog,
												int which) {
											dialog.dismiss();
											JobDetailActivity.this.finish();
										}
									}).create();
					dialog.show();	
					ContentResolver cr = mContext.getContentResolver();

					/* insert new */
					ContentValues values = new ContentValues();	
					number = intent.getStringExtra("number");
				
					Cursor c = cr.query(JobProvider.CONTENT_URI, new String[] 
								{
								JobProvider.VOLUMN_NUMBER + " as _id",
								JobProvider.VOLUMN_CREATE_TIME, 
								JobProvider.VOLUMN_EXECUTOR,
								JobProvider.VOLUMN_POI_LIST,
								}, "number =?", new String[]{number}, null);
					c.moveToFirst();
					int id = c.getColumnIndex(JobProvider.VOLUMN_CREATE_TIME);
					final String c_time = c.getString(id);
					values.put(JobFinishedProvider.VOLUMN_NUMBER,number);
					values.put(JobFinishedProvider.VOLUMN_STATUS, "finished");
					values.put(JobFinishedProvider.VOLUMN_CREATE_TIME, c_time);
					values.put(JobFinishedProvider.VOLUMN_FINISH_TIME,f_time);
					
					c.moveToFirst();
					int id1 = c.getColumnIndex(JobProvider.VOLUMN_EXECUTOR);
					final String executor = c.getString(id1);
					values.put(JobFinishedProvider.VOLUMN_EXECUTOR,executor);
					
					c.moveToFirst();
					int id2 = c.getColumnIndex(JobProvider.VOLUMN_POI_LIST);
					final String poi_list= c.getString(id2);
					values.put(JobFinishedProvider.VOLUMN_POI_LIST, poi_list);

					Uri uri = cr.insert(JobFinishedProvider.CONTENT_URI, values);
					Log.i(TAG, "cr.insert uri=" + uri);
                    int count = cr.delete(JobProvider.CONTENT_URI, "number =?", new String[]{number});
                    			
					
//					intent = new Intent(JobDetailActivity.this,
//							JobFinishedDetailActivity.class);
//					intent = getIntent();
//					intent.putExtra("number", intent.getExtras().getString("number"));
//					startActivity(intent);
				}
			});
			
			
			btng.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					//开始记录路线
//					TimerTask task = new TimerTask(){  
//					      public void run() {  
////					      Message message = new Message();      
////					      message.what = 2;      
////					      handler.sendMessage(message); 
//				    	   // TODO Auto-generated method stub
//				    	   Log.i(TAG, "run...");
//				    	   Message msg = handler.obtainMessage(startTimer);
//				    	   msg.sendToTarget();					    	  
//					   }  
//					};
//										
//					timer.schedule(task,2000, 2000); //延时1000ms后执行，1000ms执行一次
					
					//此处应有对坐标点路线的规划
					LatLng pt1 = new LatLng(mLocation.getLatitude(), mLocation
							.getLongitude());
					
					String[] posList = mPoi.split(";");
//					String[] pos = posList[0].split(",");
					String[][] poso = new String[posList.length][];
					String[][] min ;
					for (int i = 0 ; i < posList.length ;i++){
						 poso[i] = posList[i].split(",");			
					}
					//分段导航
//					for(int k = 0 ; k <posList.length ; k++){
						String[] myLocation = new String[2];
						myLocation[0] = String.valueOf(mLocation.getLatitude());
						myLocation[1] = String.valueOf(mLocation.getLongitude());
						
						min = mindistance(myLocation , poso);										
//						LatLng pt1 = new LatLng(mLocation.getLatitude(), mLocation
//								.getLongitude());
						//此处目前只取了第一个点
//						String[] posList = mPoi.split(";");
//						String[] pos = mPoi.split(",");
//						String[] pos = posList[0].split(",");
//						LatLng pt2 = new LatLng(Double.parseDouble(pos[0]), Double
//								.parseDouble(pos[1]));
						LatLng pt2 = new LatLng(Double.parseDouble(min[0][0]), Double
								.parseDouble(min[0][1]));
						
//						// 构建 导航参数
//						NaviPara para = new NaviPara();
//						para.startPoint = pt1;
//						para.startName = "从这里来";
//						para.endPoint = pt2;
//						para.endName = "到这里去";

//						BaiduMapNavigation.openBaiduMapNavi(para, mContext);
//						&&min[1].equals(poso[i][1])				
//						for (int i = 0 ; i <poso.length; i++){						
//							if(min[0].equals(poso[i][0])){
//								for(int j = i+1; j <poso.length; j++){
//									poso[i] = poso[j];
//								}
//								
//							}
//						}
						
						Intent intent = new Intent(JobDetailActivity.this, RoutePlanDemo.class);
						Bundle bundle = new Bundle();
						bundle.putString("number", number);
						bundle.putString("pt1", myLocation[0] + ";" + myLocation[1]);
						bundle.putString("pt2", min[0][0] + ";" + min[0][1]);
						intent.putExtras(bundle);
						startActivity(intent);
						
						for(int i =Integer.parseInt(min[1][0]), j = i+1; j<poso.length; i++,j++){
							poso[i] = poso[j];
						}
//						poso[poso.length-1][0] = poso[poso.length-1][1]="";						
						
						String undone = poso[0][0] + "," + poso[0][1];
						for(int i = 1 ; i <poso.length-1; i++){
							undone = undone +";"+ poso[i][0] + "," + poso[i][1];
						}
						
						ContentValues values = new ContentValues();	 			            
			            values.put(JobProvider.VOLUMN_POI_LIST, undone);
						ContentResolver cr = mContext.getContentResolver();
						cr.update(JobProvider.CONTENT_URI, values, "number =?", new String[]{number});		
						
//					}
										
					
				}				
				//计算距离
//				private double distance(String[] a , String[] b){
//					double ax = Double.parseDouble(a[0]);
//					double ay = Double.parseDouble(a[1]);
//					double bx = Double.parseDouble(b[0]);
//					double by = Double.parseDouble(b[1]);
//					
//					double dis = Math.sqrt((ax-bx)*(ax-bx)+(ay-by)*(ay-by));
//					return dis;		
//				}
				private double distance(String[] a , String[] b){
					double lat1 = Double.parseDouble(a[0]);
					double lng1 = Double.parseDouble(a[1]);
					double lat2 = Double.parseDouble(b[0]);
					double lng2 = Double.parseDouble(b[1]);
					double radLat1 = lat1 * Math.PI / 180;
					double radLat2 = lat2 * Math.PI / 180;
					double aa = radLat1 - radLat2;
					double bb = lng1 * Math.PI / 180 - lng2 * Math.PI / 180;
					double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(aa / 2), 2)
					+ Math.cos(radLat1) * Math.cos(radLat2)
					* Math.pow(Math.sin(bb / 2), 2)));
					s = s * 6378137.0;
					s = Math.round(s * 10000) / 10000;
					return s;	
				}
				
				private String[][] mindistance(String[] a , String[][] b){
					String[][] min = new String[2][2];
					double dis ;
					min[0] = b[0];
					dis = distance(a , b[0]);		
					for (int i=1;i<b.length;i++){			
						min[0] = dis < distance(a , b[i]) ? min[0] : b[i];
						dis = dis < distance(a , b[i]) ? dis : distance(a , b[i]);
					}
					for(int i=0;i<b.length;i++){
						if(min[0].equals(b[i])){				
							min[1][0] = min[1][1] ="" + i;	
						}
					}
					return min;
					
				}				
			});
			super.handleMessage(msg);
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// mLocationClient = new LocationClient(getApplicationContext()); //
		// 声明LocationClient类
		// mLocationClient.registerLocationListener(myListener); // 注册监听函数

		mContext = JobDetailActivity.this;

		mLayoutInflater = LayoutInflater.from(this);
		
		intent = getIntent();
	    number = intent.getExtras().getString("number");
		Log.i(TAG, "number=" + number);

		ContentResolver cr = mContext.getContentResolver();
		Cursor c = cr.query(JobProvider.CONTENT_URI, new String[] {
				JobProvider.VOLUMN_NUMBER + " as _id",
				JobProvider.VOLUMN_CREATE_TIME,
				JobProvider.VOLUMN_EXECUTOR,
				JobProvider.VOLUMN_POI_LIST 
				}, "number=?",
				new String[] { number }, null);
		
		String c_time = null;
		String executor = null;
		String poi = null;
		if (c != null) {
			if (c.moveToFirst()) {
//				 do {
				c_time = c.getString(1);
				executor = c.getString(2);
				poi = c.getString(3);
//				 } while (c.moveToNext());
			}
			c.close();
		}
		Log.i(TAG, "poi=" + poi + ", executor=" + executor);
		mPoi = poi;

		setContentView(R.layout.job_detail);

		TextView tv = (TextView) findViewById(R.id.textView1);
		tv.setText(tv.getText() + number);
		tv = (TextView) findViewById(R.id.textView2);
		tv.setText(tv.getText() + executor);
		tv = (TextView) findViewById(R.id.textView3);
		tv.setText(tv.getText() + c_time);
		tv = (TextView) findViewById(R.id.textView4);
		tv.setText(tv.getText() + poi);

		mMapView = (MapView) findViewById(R.id.mapView);
		mBaiduMap = mMapView.getMap();

		// 开启定位图层
		mBaiduMap.setMyLocationEnabled(true);
		// 定位初始化
		mLocClient = new LocationClient(this);
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		// option.setPriority(LocationClientOption.NetWorkFirst);
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(1000);
		mLocClient.setLocOption(option);
		mLocClient.start();

		// handler.sendMessageDelayed(handler.obtainMessage(1), 2000);
		super.onCreate(savedInstanceState);
	}

	// public class MyLocationListener implements BDLocationListener {
	// @Override
	// public void onReceiveLocation(BDLocation location) {
	// Log.i(TAG, "onReceiveLocation location=" + location);
	// if (location == null)
	// return;
	// StringBuffer sb = new StringBuffer(256);
	// sb.append("time : ");
	// sb.append(location.getTime());
	// sb.append("\nerror code : ");
	// sb.append(location.getLocType());
	// sb.append("\nlatitude : ");
	// sb.append(location.getLatitude());
	// sb.append("\nlontitude : ");
	// sb.append(location.getLongitude());
	// sb.append("\nradius : ");
	// sb.append(location.getRadius());
	// if (location.getLocType() == BDLocation.TypeGpsLocation) {
	// sb.append("\nspeed : ");
	// sb.append(location.getSpeed());
	// sb.append("\nsatellite : ");
	// sb.append(location.getSatelliteNumber());
	// } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
	// sb.append("\naddr : ");
	// sb.append(location.getAddrStr());
	// }
	//
	// Log.i(TAG, sb.toString());
	// }
	// }
	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null || mMapView == null)
				return;
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(100).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			mBaiduMap.setMyLocationData(locData);
			mLocation = location;

			handler.sendMessage(handler.obtainMessage(1));

			// if (isFirstLoc) {
			// isFirstLoc = false;
			// LatLng ll = new LatLng(location.getLatitude(),
			// location.getLongitude());
			// MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
			// mBaiduMap.animateMapStatus(u);
			// }
		}

		public void onReceivePoi(BDLocation poiLocation) {
		}
	}

	@Override
	protected void onDestroy() {
		// 退出时销毁定位
		mLocClient.stop();
		// 关闭定位图层
		mBaiduMap.setMyLocationEnabled(false);
		mMapView.onDestroy();
		mMapView = null;
		super.onDestroy();

	}
	
	

}
